package com.algebra.util.encrypt;

import org.apache.ibatis.executor.resultset.DefaultResultSetHandler;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.Configuration;

import java.lang.reflect.Field;
import java.sql.Statement;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

/**
 * @author al
 * @date 2022/5/24 15:37
 * @description 结果集查询（敏感字段解密处理拦截器）
 */
@Intercepts({@Signature(
        type = ResultSetHandler.class,
        method = "handleResultSets",
        args = {Statement.class}
)})
public class QueryDataFieldFilter implements Interceptor {

    private EncryptorProperties encryptorProperties;

    public QueryDataFieldFilter(){}

    public QueryDataFieldFilter(EncryptorProperties encryptorProperties){
        this.encryptorProperties = encryptorProperties;
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        List var2 = (List) invocation.proceed();
        if (var2.isEmpty()) {
            return var2;
        } else {
            DefaultResultSetHandler var3 = (DefaultResultSetHandler) invocation.getTarget();
            Field var4 = var3.getClass().getDeclaredField("mappedStatement");
            var4.setAccessible(true);
            MappedStatement var5 = (MappedStatement) var4.get(var3);
            Configuration var6 = var5.getConfiguration();
            Iterator var7 = var2.iterator();
            while (var7.hasNext()) {
                Object var8 = var7.next();
                if (!DataFilter.resultSet(var6, var8,
                        (a, b) -> FieldCrypt.decryptField(this.encryptorProperties, a, b))) {
                    break;
                }
            }
            return var2;
        }
    }

    @Override
    public Object plugin(Object target) {
        return target instanceof ResultSetHandler ? Plugin.wrap(target, this) : target;
    }

    @Override
    public void setProperties(Properties properties) {
    }


}
